package zero.slr;

import java.util.ArrayList;
import java.util.List;

import zero.entity.Production;

/**
 * 项目
 * 
 * @author Zero
 *
 */
public class Item extends Production implements Cloneable {
    // 小圆点的位置，表示在第几个元素的前面
    private int        pos;
    // 指向对应的产生式，如果没有则为null
    private Production production = null;

    public static Item fromProduction(Production production) {
        Item         item  = new Item();
        List<String> right = new ArrayList<>();

        right.addAll(production.getRight());
        item.setLeft(production.getLeft());
        item.setRight(right);
        item.setProduction(production);
        item.pos = 0;

        return item;
    }

    public void step() {
        ++this.pos;
    }

    @Override
    protected Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof Item)) {
            return false;
        }

        Item o = (Item) obj;

        return pos == o.getPos() && production.equals(o.getProduction());
    }

    @Override
    public String toString() {
        StringBuffer buf = new StringBuffer(getLeft());
        buf.append(" ➝");

        int i = 0;
        for (String s : getRight()) {
            if (i++ == pos) {
                buf.append("。").append(s);
            } else {
                buf.append(" ").append(s);
            }
        }

        if (pos == getRight().size()) {
            buf.append("。");
        }

        return buf.toString();
    }

    public int getPos() {
        return pos;
    }

    public void setPos(int pos) {
        this.pos = pos;
    }

    public Production getProduction() {
        return production;
    }

    public void setProduction(Production production) {
        this.production = production;
    }
}
